<?php

namespace App\Http\Controllers\IndexManage;

use App\Model\Biji;
use App\Model\Book;
use App\Facades\AjaxResponse;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class BookController extends Controller{

	/**
	 * 根据用户ID获取笔记本列表
	 *
	 * @param Request $request
	 * @return mixed
	 */
    public function index(Request $request){
    	$user_id = session('user_id');
    	if($user_id){
    		$search['book_title'] = $request->input('search_book');
			$select_fields = [
				Book::FIELD_BOOK_ID,
				Book::FIELD_BOOK_TITLE,
			];
			$return['book_list'] = Book::getBooksByUserId($user_id, $search['book_title'], $select_fields);
			//根据笔记本ID获取笔记本下的笔记个数
			foreach ($return['book_list'] as $book){
				$conditions['where'][Book::FIELD_BOOK_ID] = $book[Book::FIELD_BOOK_ID];
				$book['bijis_count'] = Biji::getBijiCountByConditions($conditions);
			}
			return AjaxResponse::success($return);
		}else{
			return AjaxResponse::fail();
		}
	}

	/**
	 * 新增当前用户的笔记本
	 *
	 * @param Request $request
	 * @return mixed
	 */
	public function addBook(Request $request){
		$validator = Validator::make($request->all(), [
			'book_title' 	=> 'required|string'
		]);
		if($validator->fails()){
			return AjaxResponse::fail(AJAX_CODE_REQUEST_PARAMS_ERROR, $validator->errors()->first());
		}

		$request['book_title'] = $request->input('book_title');
		$user_id = session('user_id');

		if($user_id) {
			$conditions['where'] = [
				Book::FIELD_USER_ID => $user_id,
				Book::FIELD_BOOK_TITLE => $request['book_title'],
			];
			//验证新增的笔记本标题是否已存在
			$exist_book = Book::getBookCountByConditions($conditions);
			if(empty($exist_book)){
				$insert_data = [
					Book::FIELD_USER_ID => $user_id,
					Book::FIELD_BOOK_TITLE => $request['book_title'],
				];
				$book_id = Book::add($insert_data);
				if ($book_id) {
					$select_fields = [
						Book::FIELD_BOOK_ID,
						Book::FIELD_BOOK_TITLE,
					];
					$book = Book::getNormalBookByBookId($book_id, $select_fields);
					$return['book_info'] = $book;
					return AjaxResponse::success($return);
				} else {
					return AjaxResponse::fail(AJAX_CODE_ADD_FAIL);
				}
			}else{
				return AjaxResponse::fail(AJAX_CODE_BOOK_TITLE_REPEAT_ERROR);
			}
		}
	}
}
